// myInternet Functionality Checker (MIFC)
// Advanced Internet Services
// 11/19/2011


import java.io.IOException;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

import org.apache.commons.net.telnet.TelnetClient;

public class TelnetTester implements Runnable{

//	private static final int MIN_PORT = 0;
//	private static final int MAX_PORT = 65535;
	
	ConnectionStatus telnetStatus = new ConnectionStatus();
	ResultsTable sharedTable = new ResultsTable();
	private int numTests;
	static CyclicBarrier barrier;
	
	private static String server = "telehack.com";
	
	// results table key
	private static final String TELNET_KEY = "telnet";
	
	
	public TelnetTester(ResultsTable table, CyclicBarrier b,  int n){
		sharedTable = table;
		numTests = n;
		barrier = b;
	}
	
	
	public boolean setNewTesterServer(String serv){
		if (serv == null || serv.trim().length() == 0) {
			return false; // invalid server
		} else {
			server = serv;
			return true;
		}
	}
	
	
	private int isConnected() {
		
		TelnetClient tClient = new TelnetClient();
		try{
			tClient.connect(server, 23);
			tClient.disconnect();
			return 0;
		} catch (ConnectException e) {
			return -1; // could not connect to server
		} catch (UnknownHostException e) {
			return -2; // unknown host
		} catch (IOException e) {
			return -3;
		}
		
	}
	
	public ConnectionStatus runTests(int n) {
		
		for (int i = 0; i < n; i++){
			if (isConnected() == 0){
				this.telnetStatus.addPassedAttempt();
			} else {
				this.telnetStatus.addFailedAttempt();
			}
		}
		return this.telnetStatus;
		
	}


	@Override
	public void run() {
		// run the tests and add it to the table
		System.out.println("IN TELNET RUN");
		
		telnetStatus = runTests(numTests);
		sharedTable.addResult(TELNET_KEY, telnetStatus);
		
	
		try {
			barrier.await();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BrokenBarrierException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	
	
}
